import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import './characteristicTile.dart';

class Device extends StatefulWidget {
  final BluetoothDevice device;

  const Device({super.key, required this.device});

  @override
  State<Device> createState() => _Content();
}

class _Content extends State<Device> {
  List<BluetoothService> _services = [];

  BluetoothConnectionState _connectionState =
      BluetoothConnectionState.disconnected;

  late StreamSubscription<BluetoothConnectionState>
      _connectionStateSubscription;

  bool get isConnected {
    return _connectionState == BluetoothConnectionState.connected;
  }

  // 设置监听
  Future<void> setListen() async {
    _connectionStateSubscription =
        widget.device.connectionState.listen((state) async {
      _connectionState = state;
      if (state == BluetoothConnectionState.connected) {
        _services = [];
      }
      if (mounted) {
        setState(() {});
      }
    });
  }

  // 连接设备
  void connect() async {
    try {
      await widget.device.connect();
      debugPrint('connectSuccess________________>>>>>>>>>>>');
    } catch (e) {
      debugPrint('error________________>>>>>>>>>>>$e');
    }
  }

  // 断开连接
  void disconnect() {
    widget.device.disconnect();
  }

  Future<void> initDevice() async {
    await setListen();
    connect();
  }

  @override
  void initState() {
    initDevice();
    super.initState();
  }

  @override
  void dispose() {
    _connectionStateSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('device')),
        body: Column(
          children: [
            ListTile(
              title: Text(
                  'Device is ${_connectionState.toString().split('.')[1]}.'),
              trailing: TextButton(
                onPressed: () async {
                  if (!isConnected) {
                    // Get.snackbar('title', '请先连接蓝牙设备');
                    debugPrint('请先连接蓝牙设备');
                    return;
                  }
                  _services = await widget.device.discoverServices();
                  debugPrint('_services-------------->>>>>>>>>>>$_services');
                  setState(() {});
                },
                child: const Text("Get Services"),
              ),
            ),
            Expanded(
              child:  ListView(
                children: _buildServiceTiles(),
              ),)
          ],
        ),
        floatingActionButton: isConnected
            ? FloatingActionButton(
                backgroundColor: Colors.red,
                onPressed: disconnect,
                child: const Text('disconnect'),
              )
            : FloatingActionButton(
                onPressed: connect,
                child: const Text('connect'),
              ));
  }

List<Widget> _buildServiceTiles() {
  return _services.map((service) {
      return ExpansionTile(
        title: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            const Text('Service', style: TextStyle(color: Colors.blue)),
            Text(
              '0x${service.uuid.str.toUpperCase()}',
            ),
          ],
        ),
        children: service.characteristics.map((c) {
          return CharacteristicTile(
            characteristic: c,
            device: widget.device,
            descriptorTiles: c.descriptors
                .map((d) => DescriptorTile(descriptor: d))
                .toList(),
          );
        }).toList(),
      );
    },
  ).toList();
}
}
